import sys, os

def call(args, options, global_options):
    from uliweb.core.SimpleFrame import Dispatcher
    from uliweb.orm import Begin, Commit, Rollback

    app = Dispatcher(apps_dir=global_options.apps_dir, start=False)
    Begin()
    try:
        process(args, options, global_options)
        Commit()
    except:
        Rollback()
        import traceback
        traceback.print_exc()

def process(args, options, global_options):
    print 'Processing sign_tmp file...'
    if len(args) != 2:
        print "Error, the command line is not right"
        print "     uliweb [options] call import_workload dir"
        return
        
    import_(args[1], options, global_options)
        
def import_(dir, options, global_options):
    import csv
    from uliweb.orm import get_model
    from glob import glob
    from datetime import date
    from decimal import Decimal
    from sqlalchemy.sql import func, select
    
    ResourceHis = get_model('resourcehis')
    
    filenames = glob(os.path.join(dir, 'sign_tmp_*'))
    if len(filenames) > 0:
        filename = filenames[0]
    else:
        filename = None
    if not filename:
        print "Can't find the sign_tmp file in %s" % dir
        return
    
    t_date = date.today()
    mon = t_date.month
    year = t_date.year
    if mon>1:
        mon = mon-1
    else:
        mon = 12
        year = year-1
    yearmon = year*100 + mon
    
    ResourceHis.table.update(ResourceHis.c.yearmon==yearmon).execute(workday=0, worktime=0)
    
    d = {}
    for line in csv.reader(open(filename), delimiter='|'):
        v = line
        login_name = unicode(v[2], 'utf-8')
        if v[9]:
            worktime = int(v[9])
        else:
            continue
        
        x = d.setdefault(login_name, {'workday':0, 'worktime':0})
        x['workday'] += 1
        x['worktime'] += worktime
        
    c_n = 0
    n_n = 0
    n = 0
    for v in select([ResourceHis.c.user, func.sum(ResourceHis.c.workload), func.count()],
            (ResourceHis.c.yearmon==yearmon)).group_by(ResourceHis.c.user).execute():
        n += 1
        user, s, count = v
        
        v = d.get(user, {})
        if not v:
            n_n += 1
            if global_options.verbose:
                print 'skip', 'login_name=', user
            continue
        if count == 1 or s == Decimal('0.0'):
            ResourceHis.table.update((ResourceHis.c.yearmon==yearmon) & (ResourceHis.c.user==user)).execute(workday=v['workday'], worktime=Decimal(str(v['worktime']/8.0/count)))
        else:
            for row in ResourceHis.filter((ResourceHis.c.yearmon==yearmon) & (ResourceHis.c.user==user)):
                row.workday = v['workday']
                row.worktime = Decimal(str(v['worktime']/8.0*float(row.workload/s)))
                row.save()
                
        c_n += 1
        
    os.rename(filename, os.path.join(os.path.dirname(filename), 'bak_' + os.path.basename(filename)))
    print "Total process %d, and skipped %d, changed %d" % (n, n_n, c_n)
